Ext.namespace("Microtraining.Admin.Paper");
Mt = Microtraining.Admin;
Mt.Paper={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示试卷的视图相对试卷列表Grid的位置
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示试卷信息页(或者打开新窗口)
			 */
			IsFix:0
		}
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Paper.Cookie.get('View.Direction')){
			Mt.Paper.Config.View.Direction=Mt.Paper.Cookie.get('View.Direction');
		}
		if (Mt.Paper.Cookie.get('View.IsFix')!=null){
			Mt.Paper.Config.View.IsFix=Mt.Paper.Cookie.get('View.IsFix');
		}
	}
};
/**
 * Model:数据模型
 */
Mt.Paper.Store = {
	/**
	 * 试卷
	 */
	paperStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
                {name: 'paper_id',type: 'int'},
                {name: 'company_id',type: 'int'},
                {name: 'company_name',type: 'string'},
                {name: 'paper_title',type: 'string'},
                {name: 'point',type: 'float'},
                {name: 'questionStr',type: 'string'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Paper.Config.PageSize;
					Ext.apply(options.params, Mt.Paper.View.Running.paperGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),
    /**
     * 企业
     */
    companyStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/company.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'companys',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'company_id'
        }, [
            {name: 'company_id', mapping: 'company_id'},
            {name: 'company_name', mapping: 'company_name'}
        ])
    }),
    /**
     * 考试
     */
    testStore:new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalCount',
            successProperty: 'success',
            root: 'data',remoteSort: true,
            fields : [
                {name: 'test_id',type: 'int'},
                {name: 'company_name',type: 'string'},
                {name: 'test_title',type: 'string'},
                {name: 'paper_title',type: 'string'},
                {name: 'paper_json',type: 'string'},
                {name: 'begin_time',type: 'date',dateFormat:'Y-m-d H:i:s'},
                {name: 'end_time',type: 'date',dateFormat:'Y-m-d H:i:s'}
            ]}
        ),
        writer: new Ext.data.JsonWriter({
            encode: false 
        }),
        listeners : {
            beforeload : function(store, options) {
                if (Ext.isReady) {
                    if (!options.params.limit)options.params.limit=Mt.Paper.Config.PageSize;
                    Ext.apply(options.params, Mt.Paper.View.Running.testGrid.filter);//保证分页也将查询条件带上
                }
            }
        }
    }),
    /**
     * 题目
     */
    selectQuestionStore:new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalCount',
            successProperty: 'success',
            root: 'data',remoteSort: true,
            fields : [
                {name: 'question_id',type: 'int'},
                {name: 'company_id',type: 'int'},
                {name: 'company_name',type: 'string'},
                {name: 'question_title',type: 'string'},
                {name: 'paper_title',type: 'string'},
                {name: 'answer',type: 'string'},
                {name: 'point',type: 'float'},
                {name: 'options_json',type: 'string'},
                {name: 'options_jsonShow',type:'string'},
                {name: 'paperStr',type: 'string'}
            ]}
        ),
        writer: new Ext.data.JsonWriter({
            encode: false
        }),
        listeners : {
            beforeload : function(store, options) {
                if (Ext.isReady) {
                    Ext.apply(options.params, Mt.Paper.View.Running.selectQuestionWindow.questionGrid.filter);//保证分页也将查询条件带上
                }
            },
            load : function(records,options){
                if (records&&records.data&&records.data.items) {
                    var selData    = Mt.Paper.View.Running.selectQuestionWindow.selData;//选中的题目
                    var data       = records.data.items;
                    //把已经推荐的题目选中
                    var sm=Mt.Paper.View.Running.selectQuestionWindow.questionGrid.sm;
                    var rows=Mt.Paper.View.Running.selectQuestionWindow.questionGrid.getView().getRows();
                    for(var i=0;i<rows.length;i++){
                        if(selData[data[i]['data'].question_id]){
                            sm.selectRow(i, true);
                        }
                    }
                }
            }
        }
    }),
    /**
     * 企业
     */
    companyStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/company.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'companys',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'company_id'
        }, [
            {name: 'company_id', mapping: 'company_id'},
            {name: 'company_name', mapping: 'company_name'}
        ])
    }),
    /**
	 * 试卷
	 */
	paperStoreForCombo:new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
		  url: 'home/admin/src/httpdata/paper.php'
		}),
		reader: new Ext.data.JsonReader({
		  root: 'papers',
		  autoLoad: true,
		  totalProperty: 'totalCount',
		  idProperty: 'paper_id'
		}, [
		  {name: 'paper_id', mapping: 'paper_id'},
		  {name: 'paper_title', mapping: 'paper_title'}
		])
	})
};
/**
 * View:试卷显示组件
 */
Mt.Paper.View={
	/**
	 * 编辑窗口：新建或者修改试卷
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					}
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
              {xtype: 'hidden',name : 'paper_id',ref:'../paper_id'},
              /*{xtype: 'hidden',name : 'company_id',ref:'../company_id'},
              {
                   fieldLabel : '企业',xtype: 'combo',name : 'company_name',ref : '../company_name',
                   store:Mt.Paper.Store.companyStoreForCombo,emptyText: '请选择企业',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Paper.Config.PageSize,
                   displayField:'company_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                           '<h3>{company_name}</h3>',
                       '</div></tpl>'
                   ),
                   listeners:{
                       'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                       if(this.fireEvent('beforeselect', this, record, index) !== false){
                          this.grid.company_id.setValue(record.data.company_id);
                          this.grid.company_name.setValue(record.data.company_name);
                          this.collapse();
                       }
                   }
              },*/
              {fieldLabel : '试卷名',name : 'paper_title'}
              // {fieldLabel : '分值',name : 'point',xtype : 'numberfield'}
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {

						if (!this.editForm.getForm().isValid()) {
							return;
						}
						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServicePaper.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Paper.View.Running.paperGrid.doSelectPaper();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServicePaper.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Paper.View.Running.paperGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Paper.View.Running.paperGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected());

					}
				}]
			}, config);
			Mt.Paper.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示试卷详情
	 */
	PaperView:{
		/**
		 * Tab页：容器包含显示与试卷所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择试卷！');
									return false;
								}
								Mt.Paper.Config.View.IsShow=1;
								Mt.Paper.View.Running.paperGrid.showPaper();
								Mt.Paper.View.Running.paperGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Paper.View.PaperView.Tabs.superclass.constructor.call(this, config);
                Mt.Paper.View.Running.testGrid=new Mt.Paper.View.TestView.Grid();
				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Paper.Config.View.Direction==1)||(Mt.Paper.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabPaperDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
             '    <tr class="entry"><td class="head">企业</td><td class="content">{company_name}</td></tr>',
             '    <tr class="entry"><td class="head">试卷名</td><td class="content">{paper_title}</td></tr>',
             // '    <tr class="entry"><td class="head">分值</td><td class="content">{point}</td></tr>',
						 '</table>'
					 ]}
				);
                /*this.add(
                    {title: '考试',iconCls:'tabs',tabWidth:150,
                     items:[Mt.Paper.View.Running.testGrid]
                    }
                );*/
			}
		}),
		/**
		 * 窗口:显示试卷信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看试卷",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Paper.View.PaperView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Paper.Config.View.IsShow=0;
							Mt.Paper.View.Running.paperGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Paper.View.Running.paperGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增试卷',scope:this,
						handler : function() {this.hide();Mt.Paper.View.Running.paperGrid.addPaper();}
					},{
						text: '修改试卷',scope:this,
						handler : function() {this.hide();Mt.Paper.View.Running.paperGrid.updatePaper();}
					}]
				}, config);
				Mt.Paper.View.PaperView.Window.superclass.constructor.call(this, config);
			}
		})
	},
	/**
	 * 视图：考试列表
	 */
	TestView:{
		/**
		 *  当前创建的考试编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改考试
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						},
                        afterrender:function(){
                            switch (Mt.Paper.Config.OnlineEditor)
                            {
                                case 2:
                                    Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json = KindEditor.create('textarea[name="paper_json"]',{width:'98%',minHeith:'350px', filterMode:true});
                                    break
                                case 3:
                                    pageInit_paper_json();
                                    break
                                default:
                                    ckeditor_replace_paper_json();
                            }
                        }
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                                {xtype: 'hidden',name : 'test_id',ref:'../test_id'},
                                {xtype: 'hidden',name : 'company_id',ref:'../company_id'},
                                {
                                     fieldLabel : '企业',xtype: 'combo',name : 'company_name',ref : '../company_name',
                                     store:Mt.Paper.Store.companyStoreForCombo,emptyText: '请选择企业',itemSelector: 'div.search-item',
                                     loadingText: '查询中...',width: 570, pageSize:Mt.Paper.Config.PageSize,
                                     displayField:'company_name',grid:this,
                                     mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                                     forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                                     tpl:new Ext.XTemplate(
                                         '<tpl for="."><div class="search-item">',
                                             '<h3>{company_name}</h3>',
                                         '</div></tpl>'
                                     ),
                                     listeners:{
                                         'beforequery': function(event){delete event.combo.lastQuery;}
                                     },
                                     onSelect:function(record,index){
                                         if(this.fireEvent('beforeselect', this, record, index) !== false){
                                            this.grid.company_id.setValue(record.data.company_id);
                                            this.grid.company_name.setValue(record.data.company_name);
                                            this.collapse();
                                         }
                                     }
                                },
                                {fieldLabel : '测试名',name : 'test_title'},
                                {xtype: 'hidden',name : 'paper_id',ref:'../paper_id'},
                                {fieldLabel : '考试试卷',name : 'paper_json',xtype : 'textarea',id:'paper_json',ref:'paper_json'},
                                {fieldLabel : '开考时间',name : 'begin_time',xtype : 'datefield',format : "Y-m-d"},
                                {fieldLabel : '交卷时间',name : 'end_time',xtype : 'datefield',format : "Y-m-d"}
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {
                            switch (Mt.Paper.Config.OnlineEditor)
                            {
                                case 2:
                                    if (Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json)this.editForm.paper_json.setValue(Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json.html());
                                    break
                                case 3:
                                    if (xhEditor_paper_json)this.editForm.paper_json.setValue(xhEditor_paper_json.getSource());
                                    break
                                default:
                                    if (CKEDITOR.instances.paper_json) this.editForm.paper_json.setValue(CKEDITOR.instances.paper_json.getData());
                            }

							if (!this.editForm.getForm().isValid()) {
								return;
							}
							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServiceTest.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Paper.View.Running.testGrid.doSelectTest();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServiceTest.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Paper.View.Running.testGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Paper.View.Running.testGrid.getSelectionModel().getSelected());
                            switch (Mt.Paper.Config.OnlineEditor)
                            {
                                case 2:
                                    if (Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json) Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json.html(Mt.Paper.View.Running.testGrid.getSelectionModel().getSelected().data.paper_json);
                                    break
                                case 3:
                                    break
                                default:
                                    if (CKEDITOR.instances.paper_json) CKEDITOR.instances.paper_json.setData(Mt.Paper.View.Running.testGrid.getSelectionModel().getSelected().data.paper_json);
                            }

						}
					}]
				}, config);
				Mt.Paper.View.TestView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：考试列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Paper.Store.testStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'test_id',hidden:true},
              // {header : '企业',dataIndex : 'company_name'},
              {header : '测试名',dataIndex : 'test_title'},
              {header : '考试试卷',dataIndex : 'paper_json'},
              {header : '开考时间',dataIndex : 'begin_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
              {header : '交卷时间',dataIndex : 'end_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},'-',{
										text : '添加考试',iconCls : 'icon-add',
										handler : function() {
											this.addTest();
										}
									},'-',{
										text : '修改考试',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updateTest();
										}
									},'-',{
										text : '删除考试', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deleteTest();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Paper.Config.PageSize,
						store: Mt.Paper.Store.testStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Paper.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Paper.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Paper.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectTest();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Paper.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Paper.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectTest();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 考试数据模型获取数据Direct调用
				 */
				Mt.Paper.Store.testStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServiceTest.queryPageTest}
				});
				Mt.Paper.View.TestView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的考试
			 */
			doSelectTest : function() {
				if (Mt.Paper.View.Running.paperGrid&&Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected()){
					var paper_id = Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected().data.paper_id;
					var condition = {'paper_id':paper_id,'start':0,'limit':Mt.Paper.Config.PageSize};
					this.filter       ={'paper_id':paper_id};
					ExtServiceTest.queryPageTest(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result           = new Array();
								result['data']       =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Paper.Store.testStore.loadData(result);
							} else {
								Mt.Paper.Store.testStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的考试！');
							}

							if (Mt.Paper.Store.testStore.getTotalCount()>Mt.Paper.Config.PageSize){
								 Mt.Paper.View.Running.testGrid.bottomToolbar.show();
							}else{
								 Mt.Paper.View.Running.testGrid.bottomToolbar.hide();
							}
							Mt.Paper.View.Running.paperGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建考试
			 */
			addTest : function(){
				if (Mt.Paper.View.TestView.edit_window==null){
					Mt.Paper.View.TestView.edit_window=new Mt.Paper.View.TestView.EditWindow();
				}
				Mt.Paper.View.TestView.edit_window.resetBtn.setVisible(false);
				Mt.Paper.View.TestView.edit_window.saveBtn.setText('保 存');
				Mt.Paper.View.TestView.edit_window.setTitle('添加考试');
				Mt.Paper.View.TestView.edit_window.savetype=0;
				Mt.Paper.View.TestView.edit_window.test_id.setValue("");
				var company_id = Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected().data.paper_id;
				Mt.Paper.View.TestView.edit_window.paper_id.setValue(company_id);
                switch (Mt.Paper.Config.OnlineEditor)
                {
                    case 2:
                        if (Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json) Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json.html("");
                        break
                    case 3:
                        break
                    default:
                        if (CKEDITOR.instances.paper_json) CKEDITOR.instances.paper_json.setData("");
                }

				Mt.Paper.View.TestView.edit_window.show();
				Mt.Paper.View.TestView.edit_window.maximize();
			},
			/**
			 * 编辑考试时先获得选中的考试信息
			 */
			updateTest : function() {
				if (Mt.Paper.View.TestView.edit_window==null){
					Mt.Paper.View.TestView.edit_window=new Mt.Paper.View.TestView.EditWindow();
				}
				Mt.Paper.View.TestView.edit_window.saveBtn.setText('修 改');
				Mt.Paper.View.TestView.edit_window.resetBtn.setVisible(true);
				Mt.Paper.View.TestView.edit_window.setTitle('修改考试');
				Mt.Paper.View.TestView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Paper.View.TestView.edit_window.savetype=1;
                switch (Mt.Paper.Config.OnlineEditor)
                {
                    case 2:
                        if (Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json) Mt.Paper.View.TestView.EditWindow.KindEditor_paper_json.html(this.getSelectionModel().getSelected().data.paper_json);
                        break
                    case 3:
                        if (xhEditor_paper_json)xhEditor_paper_json.setSource(this.getSelectionModel().getSelected().data.paper_json);
                        break
                    default:
                        if (CKEDITOR.instances.paper_json) CKEDITOR.instances.paper_json.setData(this.getSelectionModel().getSelected().data.paper_json);
                }

				Mt.Paper.View.TestView.edit_window.show();
				Mt.Paper.View.TestView.edit_window.maximize();
			},
			/**
			 * 删除考试
			 */
			deleteTest : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的考试吗?', this.confirmDeleteTest,this);
			},
			/**
			 * 确认删除考试
			 */
			confirmDeleteTest : function(btn) {
				if (btn == 'yes') {
					var del_test_ids ="";
					var selectedRows    = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_test_ids=del_test_ids+selectedRows[flag].data.test_id+",";
					}
					ExtServiceTest.deleteByIds(del_test_ids);
					this.doSelectTest();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
    /**
     * 视图：题目
     */
    QuestionView:{
        SelectQuestionWindow:Ext.extend(Ext.Window,{
            constructor : function(config) {
                config = Ext.apply({
                    selData:null,//选中的题目
                    oldData:null,//已关联的题目
                    title:"选择题目",updateData:null,closeAction:"hide",constrainHeader:true,maximizable:true,collapsible:true,
                    width:720,minWidth:720,height:560,minHeight:450,layout:'fit',plain : true,buttonAlign : 'center',
                    defaults : {autoScroll : true,},
                    listeners:{
                        beforehide:this.doHide
                    },
                    items : [new Mt.Paper.View.QuestionView.QuestionGrid({ref:"questionGrid"})],
                    buttons : [ {
                        text: "确定",ref : "../saveBtn",scope:this,
                        handler : function() {
                            var selData = this.selData;
                            var oldData = this.oldData;
                            //试卷标识
                            var paper_id=Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected().data.paper_id;
                            var condition={'selData':selData,"oldData":oldData,"paper_id":paper_id};
                            Ext.Msg.show({
                                title: '请等待', msg: '操作进行中，请稍后...',
                                animEl: 'loading', icon: Ext.Msg.WARNING,
                                closable: true, progress: true, progressText: '', width: 300
                            });
                            ExtServicePaper.updatePaperQuestion(condition,function(provider, response) {
                                if (response.result.success==true) {
                                    var msg = "操作成功！";
                                    if(response.result.del){
                                        msg += "<font color=red>取消</font>了<font color=red>"+response.result.del+"</font>件关联货品,";
                                    }
                                    if(response.result.add){
                                        msg += "<font color=green>添加</font>了<font color=green>"+response.result.add+"</font>件关联货品";
                                    }
                                    Ext.Msg.alert('提示', msg);
                                } else {
                                    Mt.Paper.Store.selectQuestionStore.removeAll();
                                    Ext.Msg.alert('提示', '操作失败！');
                                }
                                Mt.Paper.View.Running.selectQuestionWindow.hideWindow();
                                Mt.Paper.View.Running.paperGrid.doSelectPaper();
                            });
                        }
                    }, {
                        text : "取 消",scope:this,
                        handler : function() {
                            this.hide();
                        }
                    }]
                }, config);
                Mt.Paper.View.QuestionView.SelectQuestionWindow.superclass.constructor.call(this, config);
            },
            /**
            * 根据选择的题目,改变标题
            */
            changeTitle: function(){
                var title   = "选择 题目";
                var selData = this.selData;
                var count   = this.objElCount(selData);
                if(count){
                    title += "（已经选择了<font color=green>"+count+"</font>件题目）";
                }else{
                    title += "（尚未选择任何题目）";
                }
                this.setTitle(title);
            },
            /**
            * 判断自定义对象元素个数
            */
            objElCount: function(obj){
                var count = 0;
                for(var n in obj){count++}
                return count;
            },
            /**
             * 确认取消图片处理
             * con:选择窗口
             */
            doHide: function (con) {
                //window初始化时会调用,此时con为null
                if(con){
                    Ext.MessageBox.show({
                        title:'提示',msg:'确定要取消么?<br /><font color=red>(所做操作将不会保存!)</font>',buttons:Ext.MessageBox.YESNO,icon:Ext.MessageBox.QUESTION,
                        params:{con:con},
                        fn:function(btn,text,opt) {
                            if(btn=='yes') {
                                con.hideWindow();
                            }
                        }
                    });
                    return false;
                }
            },
            /**
             * 隐藏窗口
             */
            hideWindow: function () {
                //移除beforehide事件，为了防止hide时进入死循环
                this.un('beforehide',this.doHide);
                this.hide();
                this.addListener('beforehide',this.doHide);
            }
        }),
        QuestionGrid:Ext.extend(Ext.grid.GridPanel,{
            constructor : function(config) {
                config = Ext.apply({
                    /**
                     * 查询条件
                     */
                    filter:null,paper_id:null,region : 'center',store : Mt.Paper.Store.selectQuestionStore,sm : this.sm,
                    trackMouseOver : true,enableColumnMove : true,columnLines : true,loadMask : true,stripeRows : true,headerAsText : false,
                    loadMask : {msg : '加载数据中，请稍候...'},
                    defaults : {autoScroll : true},
                    cm : new Ext.grid.ColumnModel({
                        defaults:{width:120,sortable : true},
                        columns : [
                            this.sm,
                            {header : '标识',dataIndex : 'question_id',hidden:true},
                            // {header : '企业',dataIndex : 'company_name'},
                            {header : '题目',dataIndex : 'question_title'},
                            {header : '分值',dataIndex : 'point'},
                            {header : '试卷',dataIndex : 'paper_title'}
                        ]
                    }),
                    tbar : {
                        xtype : 'container',layout : 'anchor',
                        height : 27,style:'font-size:14px',
                        defaults : {
                            height : 27,anchor : '100%'
                        },
                        items : [
                            new Ext.Toolbar({
                                enableOverflow: true,width : 80,ref:'menus',
                                defaults : {
                                    xtype : 'textfield',
                                    listeners : {
                                       specialkey : function(field, e) {
                                            if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectQuestion();
                                        }
                                    }
                                },
                                items : [
                                    {text: '全部',ref:'../../isSelect',xtype:'tbsplit',iconCls : 'icon-view',enableToggle: true,
                                         toggleHandler:function(item, checked){
                                            if (checked==true){
                                                Mt.Paper.View.Running.selectQuestionWindow.questionGrid.topToolbar.menus.select.setChecked(true);
                                            }else{
                                                Mt.Paper.View.Running.selectQuestionWindow.questionGrid.topToolbar.menus.all.setChecked(true);
                                            }
                                        },
                                        menu: {
                                            items: [
                                                {text: '全部',checked: true,group: 'isSelect',ref:'../../all',
                                                    checkHandler: function(item, checked){
                                                        if (checked){
                                                            Mt.Paper.View.Running.selectQuestionWindow.questionGrid.isSelect.setText(item.text);
                                                            Mt.Paper.View.Running.selectQuestionWindow.questionGrid.filter.selectType=0;
                                                        }
                                                        Mt.Paper.View.Running.selectQuestionWindow.questionGrid.doSelectQuestion();
                                                    }
                                                },
                                                {text: '未选择',checked: false,group: 'isSelect',ref:'../../unselect',
                                                      checkHandler: function(item, checked){
                                                          if (checked){
                                                              Mt.Paper.View.Running.selectQuestionWindow.questionGrid.isSelect.setText(item.text);
                                                              Mt.Paper.View.Running.selectQuestionWindow.questionGrid.filter.selectType=2;
                                                          }
                                                          Mt.Paper.View.Running.selectQuestionWindow.questionGrid.doSelectQuestion();
                                                      }
                                                },
                                                {text: '已选择',checked: false,group: 'isSelect',ref:'../../select',
                                                      checkHandler: function(item, checked){
                                                          if (checked){
                                                              Mt.Paper.View.Running.selectQuestionWindow.questionGrid.isSelect.setText(item.text);
                                                              Mt.Paper.View.Running.selectQuestionWindow.questionGrid.filter.selectType=1;
                                                          }
                                                          Mt.Paper.View.Running.selectQuestionWindow.questionGrid.doSelectQuestion();
                                                    }
                                                }
                                             ]
                                        }
                                    },
                                    '试卷','&nbsp;&nbsp;',{ref: '../tpaper_id',xtype: 'combo',
					                   store:Mt.Paper.Store.paperStoreForCombo,hiddenName : 'paper_id',
					                   emptyText: '请选择试卷',itemSelector: 'div.search-item',
					                   loadingText: '查询中...',width:280,pageSize:Mt.Paper.Config.PageSize,
					                   displayField:'paper_title',valueField:'paper_id',
					                   mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
					                   forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
					                   tpl:new Ext.XTemplate(
					                     '<tpl for="."><div class="search-item">',
					                     '<h3>{paper_title}</h3>',
					                     '</div></tpl>'
					                   )
					                },'&nbsp;&nbsp;日期&nbsp;&nbsp;',
					                { ref:'../cbegin_time',xtype : 'datefield',format : "Y-m-d"},'&nbsp;-&nbsp;',
                					{ ref:'../cend_time',xtype : 'datefield',format : "Y-m-d"},'&nbsp;&nbsp;',
                                    '题目','&nbsp;&nbsp;',{ref: '../qquestion_title'},'&nbsp;&nbsp;',
                                    {
                                        xtype : 'button',text : '查询',scope: this,
                                        handler : function() {
                                            this.doSelectQuestion();
                                        }
                                    },
                                    {
                                        xtype : 'button',text : '重置',scope: this,
                                        handler : function() {
                                            this.topToolbar.tpaper_id.setValue("");
                                            this.topToolbar.qquestion_title.setValue("");
                                            this.filter={};
                                            this.doSelectQuestion();
                                        }
                                    }
                                ]
                            })
                        ]
                    },
                    bbar: new Ext.PagingToolbar({
                        pageSize: Mt.Paper.Config.PageSize,
                        store: Mt.Paper.Store.selectQuestionStore,
                        scope:this,autoShow:true,displayInfo: true,
                        displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
                        emptyMsg: "无显示数据",
                        items: [
                            {xtype:'label', text: '每页显示'},
                            {xtype:'numberfield', value:Mt.Paper.Config.PageSize,minValue:1,width:35,
                                style:'text-align:center',allowBlank:false,
                                listeners:
                                {
                                    change:function(Field, newValue, oldValue){
                                        var num = parseInt(newValue);
                                        if (isNaN(num) || !num || num<1)
                                        {
                                            num = Mt.Paper.Config.PageSize;
                                            Field.setValue(num);
                                        }
                                        Mt.Paper.Config.PageSize = num;
                                        this.ownerCt.ownerCt.doSelectQuestion();
                                    },
                                    specialKey :function(field,e){
                                        if (e.getKey() == Ext.EventObject.ENTER){
                                            var num = parseInt(field.getValue());
                                            if (isNaN(num) || !num || num<1)
                                            {
                                                num = Mt.Paper.Config.PageSize;
                                            }
                                            Mt.Paper.Config.PageSize = num;
                                            this.ownerCt.ownerCt.doSelectQuestion();
                                        }
                                    }
                                }
                            },
                            {xtype:'label', text: '个'}
                        ]
                    })
                }, config);
                //初始化显示题目列表
                //this.doSelectQuestion();
                Mt.Paper.Store.selectQuestionStore.proxy=new Ext.data.DirectProxy({
                    api: {read:ExtServicePaper.queryPagePaperQuestion}
                });
                Mt.Paper.View.QuestionView.QuestionGrid.superclass.constructor.call(this, config);
            },
            /**
            * SelectionModel
            */
            sm : new Ext.grid.CheckboxSelectionModel({
                listeners : {
                    selectionchange:function(sm) {
                        Mt.Paper.View.Running.selectQuestionWindow.changeTitle();
                        Mt.Paper.View.Running.selectQuestionWindow.questionGrid.changeFilter();
                    },
                    rowselect: function(sm, rowIndex, record) {
                        var selQuestionWin  = Mt.Paper.View.Running.selectQuestionWindow;
                        var selData      = selQuestionWin.selData;
                        var oldData      = selQuestionWin.oldData;
                        var question_id     = record.data.question_id;
                        //添加该货品ID
                        selData[question_id] = true;
                        //判断是否是已关联的货品
                        if(oldData[question_id]){
                            oldData[question_id].active = true;
                        }
                    },
                    rowdeselect: function(sm, rowIndex, record) {
                        var selQuestionWin  = Mt.Paper.View.Running.selectQuestionWindow;
                        var selData      = selQuestionWin.selData;
                        var oldData      = selQuestionWin.oldData;
                        var question_id     = record.data.question_id;
                        //删除该货品ID
                        delete selData[question_id];
                        //判断是否是已关联的货品
                        if(oldData[question_id]){
                            oldData[question_id].active = false;
                        }
                    }
                }
            }),
            doSelectQuestion : function() {
                var tmp_selQuestion=this.filter.selQuestion;
                if (this.topToolbar){
                    var paper_id=this.paper_id;
                    if (!this.filter.selectType)this.filter.selectType=0;
                    var qquestion_title = this.topToolbar.qquestion_title.getValue();
                    var tpaper_id = this.topToolbar.tpaper_id.getValue();
                    var begin_time = this.topToolbar.cbegin_time.getValue();
                    var end_time = this.topToolbar.cend_time.getValue();
                    this.filter       ={'question_title':qquestion_title,'tpaper_id':tpaper_id,'paper_id':paper_id,'selectType':this.filter.selectType,'begin_time':begin_time,'end_time':end_time};
                }
                this.filter.selQuestion=tmp_selQuestion;
                var condition = {'start':0,'limit':Mt.Paper.Config.PageSize};
                Ext.apply(condition,this.filter);
                ExtServicePaper.queryPagePaperQuestion(condition,function(provider, response) {
                    if (response.result&&response.result.data) {
                        var result           = new Array();
                        result['data']       =response.result.data;
                        result['totalCount'] =response.result.totalCount;
                        Mt.Paper.Store.selectQuestionStore.loadData(result);
                    } else {
                        Mt.Paper.Store.selectQuestionStore.removeAll();
                        Ext.Msg.alert('提示', '无符合条件的题目！');
                    }
                });
            },
            /**
            * 修改查询条件
            */
            changeFilter: function(){
                var selData =Mt.Paper.View.Running.selectQuestionWindow.selData;
                var selArr  = new Array();
                for(var x in selData){
                    selArr.push(x);
                }
                this.filter.selQuestion = selArr.join(",");
            }
        }),
    },
	/**
	 * 窗口：批量上传试卷
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传试卷数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传试卷Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow           =this;
							validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result             = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadPaper',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Paper.View.Running.paperGrid.doSelectPaper();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					}]
				}, config);
			Mt.Paper.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 视图：试卷列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Paper.Store.paperStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:120,sortable : true
					},
					columns : [
						this.sm,
                        {header : '标识',dataIndex : 'paper_id',hidden:true},
                        // {header : '企业',dataIndex : 'company_name'},
                        {header : '试卷名',dataIndex : 'paper_title'}
                        // {header : '分值',dataIndex : 'point'}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 100,
							defaults : {
								xtype : 'textfield',
								listeners : {
								   specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectPaper();
									}
								}
							},
							items : [
                                '试卷名','&nbsp;&nbsp;',{ref: '../ppaper_title'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectPaper();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                                        this.topToolbar.ppaper_title.setValue("");
										this.filter={};
										this.doSelectPaper();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加试卷',iconCls : 'icon-add',
									handler : function() {
										this.addPaper();
									}
								},'-',{
									text : '修改试卷',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updatePaper();
									}
								}/*,'-',{
									text : '删除试卷', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deletePaper();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importPaper();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入试卷',iconCls : 'icon-import',scope:this,handler:function(){this.importPaper()}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportPaper();
									}
								}*/,'-',{
									xtype:'tbsplit',text: '查看试卷', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showPaper()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hidePaper();Mt.Paper.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Paper.Cookie.set('View.IsFix',Mt.Paper.Config.View.IsFix);}}
										]}
								},'-',{
                                    text : '选择题目',ref:'../../tquestion',iconCls : 'icon-edit',disabled : true,
                                    handler : function() {
                                        if(Mt.Paper.View.Running.selectQuestionWindow==null || Mt.Paper.View.Running.selectQuestionWindow.hidden){
                                            this.showQuestion();
                                        }else{
                                            this.hideQuestion();
                                        }
                                    }
                                },'-']}
					)]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Paper.Config.PageSize,
					store: Mt.Paper.Store.paperStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Paper.Viewport){
								if (Mt.Paper.Config.View.IsShow==1){
									Mt.Paper.View.IsSelectView=1;
								}
								this.ownerCt.hidePaper();
								Mt.Paper.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Paper.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Paper.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Paper.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectPaper();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Paper.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Paper.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectPaper();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示试卷列表
			this.doSelectPaper();
			Mt.Paper.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的试卷信息Tab页
			Mt.Paper.View.Running.viewTabs=new Mt.Paper.View.PaperView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					// this.grid.btnRemove.setDisabled(sm.getCount() < 1);
					this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
                    this.grid.tquestion.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hidePaper();
						Mt.Paper.Config.View.IsShow=0;
                        this.grid.hideQuestion();
					}else{
						if (Mt.Paper.View.IsSelectView==1){
							Mt.Paper.View.IsSelectView=0;
							this.grid.showPaper();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Paper.Config.View.IsShow==1){
							Mt.Paper.View.IsSelectView=1;
						}
						this.grid.hidePaper();
						Mt.Paper.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Paper.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showPaper();
				this.tvpView.toggle(true);
			}else{
				this.hidePaper();
				Mt.Paper.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			   Mt.Paper.Config.View.IsFix=1;
			}else{
			   Mt.Paper.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Paper.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Paper.Config.View.IsShow==1){
			   this.hidePaper();
			   Mt.Paper.Config.View.IsShow=0;
			}
			this.showPaper();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的试卷
		 */
		doSelectPaper : function() {
			if (this.topToolbar){
                var ppaper_title = this.topToolbar.ppaper_title.getValue();
                this.filter       ={'paper_title':ppaper_title};
			}
			var condition = {'start':0,'limit':Mt.Paper.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServicePaper.queryPagePaper(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result           = new Array();
					result['data']       =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Paper.Store.paperStore.loadData(result);
				} else {
					Mt.Paper.Store.paperStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的试卷！');
				}
			});
		},
		/**
		 * 显示试卷视图
		 * 显示试卷的视图相对试卷列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Paper.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Paper.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Paper.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Paper.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Paper.View.Running.viewTabs);
					break;
			}
			Mt.Paper.Cookie.set('View.Direction',Mt.Paper.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Paper.Config.View.IsFix==0)&&(Mt.Paper.Config.View.IsShow==1)){
					this.showPaper();
				}
				Mt.Paper.Config.View.IsFix=1;
				Mt.Paper.View.Running.paperGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Paper.Config.View.IsShow=0;
				this.showPaper();
			}
		},
		/**
		 * 显示试卷
		 */
		showPaper : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择试卷！');
				Mt.Paper.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Paper.Config.View.IsFix==0){
				if (Mt.Paper.View.Running.view_window==null){
					Mt.Paper.View.Running.view_window=new Mt.Paper.View.PaperView.Window();
				}
				if (Mt.Paper.View.Running.view_window.hidden){
					Mt.Paper.View.Running.view_window.show();
					Mt.Paper.View.Running.view_window.winTabs.hideTabStripItem(Mt.Paper.View.Running.view_window.winTabs.tabFix);
					this.updateViewPaper();
					this.tvpView.toggle(true);
					Mt.Paper.Config.View.IsShow=1;
				}else{
					this.hidePaper();
					Mt.Paper.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Paper.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Paper.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Paper.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Paper.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Paper.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Paper.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Paper.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Paper.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Paper.View.Running.viewTabs);
					}
					break;
			}
			this.hidePaper();
			if (Mt.Paper.Config.View.IsShow==0){
				Mt.Paper.View.Running.viewTabs.enableCollapse();
				switch(Mt.Paper.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewPaper();
				this.tvpView.toggle(true);
				Mt.Paper.Config.View.IsShow=1;
			}else{
				Mt.Paper.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏试卷
		 */
		hidePaper : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Paper.View.Running.view_window!=null){
				Mt.Paper.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前试卷显示信息
		 */
		updateViewPaper : function() {
            Mt.Paper.View.Running.testGrid.doSelectTest();
			if (Mt.Paper.View.Running.view_window!=null){
				Mt.Paper.View.Running.view_window.winTabs.tabPaperDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Paper.View.Running.viewTabs.tabPaperDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建试卷
		 */
		addPaper : function() {
			if (Mt.Paper.View.Running.edit_window==null){
				Mt.Paper.View.Running.edit_window=new Mt.Paper.View.EditWindow();
			}
			Mt.Paper.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Paper.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Paper.View.Running.edit_window.setTitle('添加试卷');
			Mt.Paper.View.Running.edit_window.savetype=0;
			Mt.Paper.View.Running.edit_window.paper_id.setValue("");

			Mt.Paper.View.Running.edit_window.show();
			Mt.Paper.View.Running.edit_window.maximize();
		},
		/**
		 * 编辑试卷时先获得选中的试卷信息
		 */
		updatePaper : function() {
			if (Mt.Paper.View.Running.edit_window==null){
				Mt.Paper.View.Running.edit_window=new Mt.Paper.View.EditWindow();
			}
			Mt.Paper.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Paper.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Paper.View.Running.edit_window.setTitle('修改试卷');
			Mt.Paper.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Paper.View.Running.edit_window.savetype=1;

			Mt.Paper.View.Running.edit_window.show();
			Mt.Paper.View.Running.edit_window.maximize();
		},
		/**
		 * 删除试卷
		 */
		deletePaper : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的试卷吗?', this.confirmDeletePaper,this);
		},
		/**
		 * 确认删除试卷
		 */
		confirmDeletePaper : function(btn) {
			if (btn == 'yes') {
				var del_paper_ids ="";
				var selectedRows    = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_paper_ids=del_paper_ids+selectedRows[flag].data.paper_id+",";
				}
				ExtServicePaper.deleteByIds(del_paper_ids);
				this.doSelectPaper();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
        /**
         * 显示题目
         */
        showQuestion:function(){
            if (Mt.Paper.View.Running.selectQuestionWindow==null){
                Mt.Paper.View.Running.selectQuestionWindow=new Mt.Paper.View.QuestionView.SelectQuestionWindow();
            }
            var paper_id=Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected().data.paper_id;

            //关联题目ID组成的字符串
            var questionStr    = Mt.Paper.View.Running.paperGrid.getSelectionModel().getSelected().data.questionStr;
            var selData    = {};
            var oldData    = {};
            if(questionStr){
                var questionArr = questionStr.split(",");
                for(var i=0;i<questionArr.length;i++){
                    selData[questionArr[i]] = true;//ture为已存在的关联货品
                    oldData[questionArr[i]] = {};
                    oldData[questionArr[i]].active = true;
                }
            }
            var selQuestionWin     = Mt.Paper.View.Running.selectQuestionWindow;
            var selQuestionGrid    = selQuestionWin.questionGrid;
            selQuestionWin.selData = selData;
            selQuestionWin.oldData = oldData;
            selQuestionWin.changeTitle();//根据选择的货品,修改标题

            selQuestionGrid.paper_id = paper_id;
            if (selQuestionWin.hidden){
                Mt.Paper.View.Running.selectQuestionWindow.questionGrid.topToolbar.qquestion_title.setValue("");
                selQuestionGrid.filter = {selQuestion:questionStr};
                selQuestionGrid.topToolbar.menus.all.setChecked(true);
                selQuestionGrid.isSelect.toggle(false);
                Mt.Paper.Store.selectQuestionStore.removeAll();
            }
            selQuestionGrid.doSelectQuestion();
            selQuestionWin.show();
        },
        /**
         * 隐藏题目
         */
        hideQuestion:function(){
            if (Mt.Paper.View.Running.selectQuestionWindow!=null){
                Mt.Paper.View.Running.selectQuestionWindow.hide();
            }
        },
		/**
		 * 导出试卷
		 */
		exportPaper : function() {
			ExtServicePaper.exportPaper(this.filter,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
		/**
		 * 导入试卷
		 */
		importPaper : function() {
			if (Mt.Paper.View.current_uploadWindow==null){
				Mt.Paper.View.current_uploadWindow=new Mt.Paper.View.UploadWindow();
			}
			Mt.Paper.View.current_uploadWindow.show();
		}
	}),
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Paper.View.Running.paperGrid=new Mt.Paper.View.Grid();
			if (Mt.Paper.Config.View.IsFix==0){
				Mt.Paper.View.Running.paperGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Paper.View.Running.paperGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Paper.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Paper.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前试卷Grid对象
		 */
		paperGrid:null,
        /**
         * 当前考试Grid对象
         */
        testGrid:null,
        /**
         * 推荐题目
         */
        selectQuestionWindow:null,
		/**
		 * 显示试卷信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Paper.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Paper.Init();
	/**
	 * 试卷数据模型获取数据Direct调用
	 */
	Mt.Paper.Store.paperStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServicePaper.queryPagePaper}
	});
	/**
	 * 试卷页面布局
	 */
	Mt.Paper.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Paper.View.Panel()]
	});
	Mt.Paper.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});